package com.wildwolf.project.wildwolf.ui;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.wildwolf.project.wildwolf.service.LoginAsyncTask;
import com.wildwolf.project.wildwolf.service.aidl.IXmppFacade;
import com.wildwolf.project.wildwolf.utils.LogTagUtil;
import com.wildwolf.project.wildwolf.R;

import de.duenndns.ssl.MemorizingTrustManager;

/**
 * 连接服务器的动画显示类
 * @author Frank
 */
public class LoginAnimActivity extends Activity {

    private static final String TAG = LogTagUtil.getLogTag(LoginAnimActivity.class);
    /**
     * 服务对象
     */
    private static final Intent SERVICE_INTENT = new Intent();
    private static final int RECEIVER_PRIORITY = 50;
    static {
	SERVICE_INTENT.setComponent(new ComponentName("com.wildwolf.project.wildwolf", "com.wildwolf.project.wildwolf.WildWolfService"));
    }
    /**
     * Logo
     */
    private ImageView mLogo;
    /**
     * 登录动画
     */
    private Animation loginRotateAnim;
    private final ServiceConnection mServConn = new LoginServiceConnection();
    private IXmppFacade mXmppFacade;
    /**
     * 
     */
    private AsyncTask<IXmppFacade, Integer, Boolean> mTask;
    /**
     * 取消登录按钮
     */
    private Button cancelButton;
    private TextView mLoginState;
    private boolean mBinded;
    private BroadcastReceiver mSslReceiver;
    
    public LoginAnimActivity() {
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.login_anim);
	mLoginState = (TextView) findViewById(R.id.loginanim_status_text);
	mLogo = (ImageView) findViewById(R.id.loginanim_logo_anim);
	loginRotateAnim = AnimationUtils.loadAnimation(this, R.anim.rotate_and_scale);
	cancelButton = (Button) findViewById(R.id.loginanim_cancel_button);
	cancelButton.setOnClickListener(new ClickListener());
	mSslReceiver = new BroadcastReceiver() {
	    public void onReceive(Context ctx, Intent i) {
		try {
		    Log.i(TAG, "Interception the SSL notification");
		    PendingIntent pi = i.getParcelableExtra(MemorizingTrustManager.INTERCEPT_DECISION_INTENT_LAUNCH);
		    pi.send();
		    abortBroadcast();
		} catch (PendingIntent.CanceledException e) {
		    Log.e(TAG, "Error while displaying the SSL dialog", e);
		}
	    }
	};
    }

    @Override
    protected void onStart() {
	super.onStart();
	/**
	 * 启动登录动画
	 */
	mLogo.startAnimation(loginRotateAnim);
	if (mTask == null)
	    mTask = new LoginTask();
	if (!mBinded)
	    mBinded = bindService(LoginAnimActivity.SERVICE_INTENT, mServConn, BIND_AUTO_CREATE);
	IntentFilter filter = new IntentFilter(MemorizingTrustManager.INTERCEPT_DECISION_INTENT
		+ "/" + getPackageName());
	filter.setPriority(RECEIVER_PRIORITY);
	registerReceiver(mSslReceiver, filter);

    }
    @Override
    protected void onStop() {
	super.onStop();
	if (mBinded && mTask.getStatus() != AsyncTask.Status.RUNNING) {
	    unbindService(mServConn);
	    mXmppFacade = null;
	    mBinded = false;
	}
	/**
	 * 解除广播
	 */
	unregisterReceiver(mSslReceiver);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
	if (keyCode == KeyEvent.KEYCODE_BACK && mTask.getStatus() != AsyncTask.Status.FINISHED) {
	    if (!mTask.cancel(true)) {
		Log.d(TAG, "Can't interrupt the connection");
	    }
	    setResult(Activity.RESULT_CANCELED);
	}
	return super.onKeyDown(keyCode, event);
    }

    /**
     * 取消按钮的事件监听.
     */
    private class ClickListener implements OnClickListener {

	ClickListener() {
	}

	@Override
	public void onClick(View v) {
	    if (v == cancelButton) {
	    	/**
	    	 * 取消登录（中断）
	    	 */
		if (!mTask.cancel(true)) {
		    Log.d(TAG, "Can't interrupt the connection");
		}
		setResult(Activity.RESULT_CANCELED);
		finish();
	    }
	}
    }

    /**
     * 异步登录任务
     */
    private class LoginTask extends LoginAsyncTask {

	LoginTask() {
	}
	/**
	 *登录 任务执行完调用
	 * @param result
	 */
	@Override
	protected void onPostExecute(Boolean result) {

	    if (result == null || !result) {
		if (!result) {
		    Intent i = new Intent();
		    i.putExtra("message", getErrorMessage());
		    LoginAnimActivity.this.setResult(Activity.RESULT_CANCELED, i);
		} else
		    LoginAnimActivity.this.setResult(Activity.RESULT_CANCELED);
		LoginAnimActivity.this.finish();
	    } else {
	    	cancelButton.setEnabled(false);
		LoginAnimActivity.this.startService(LoginAnimActivity.SERVICE_INTENT);
		LoginAnimActivity.this.setResult(Activity.RESULT_OK);
		LoginAnimActivity.this.finish();
	    }
	}

	@Override
	protected void onProgressUpdate(Integer ... values) {
	    mLoginState.setText(getResources().getStringArray(R.array.loganim_state)[values[0]]);
	}

	@Override
	protected void onCancelled() {
	    super.onCancelled();
	    LoginAnimActivity.this.stopService(LoginAnimActivity.SERVICE_INTENT);
	}

    }

    /**
     * 
     */
    private class LoginServiceConnection implements ServiceConnection {

	/**
	 * Constructor.
	 */
	public LoginServiceConnection() {
	}

	@Override
	public void onServiceConnected(ComponentName name, IBinder service) {
	    mXmppFacade = IXmppFacade.Stub.asInterface(service);
	    if (mTask.getStatus() == AsyncTask.Status.PENDING)
		mTask = mTask.execute(mXmppFacade);
	}

	@Override
	public void onServiceDisconnected(ComponentName name) {
	    mXmppFacade = null;
	}
    }
}
